//------------------------------------------------------------------------
// <copyright file="GenPuid.cs" company="DevDir">
//   Copyleft (c) DevDir. No rights reserved.
// </copyright>
// <author>Nikita Sharov</author>
//------------------------------------------------------------------------

namespace DevDir.Mp3
{
  using System.Diagnostics;
  using System.Xml;
  
  public class GenPuid : IPuid
  {
    private const string processPath = @".\External\GenPuid\genpuid.exe";
    private const string key = "2bcb23fa74b43611167e47ac2dc43701";
    private const string xmlArgument = 
      @"-xml=.\External\GenPuid\Puid.xml";
    private const string xmlPath = @".\External\GenPuid\Puid.xml";

    private ProcessStartInfo psi = new ProcessStartInfo();

    public GenPuid()
    {
      this.psi.FileName = processPath;
      
      // TODO: Enable this one in the final release.
      ////this.psi.CreateNoWindow = true;
      
      this.psi.UseShellExecute = false;
      this.psi.RedirectStandardInput = false;
      this.psi.RedirectStandardOutput = false;
      this.psi.RedirectStandardError = false;
    }

    public string GetPuid(string path)
    {
      this.RunProcess(path);
      return this.RipPuid();
    }

    private void RunProcess(string path)
    {
      this.psi.Arguments = key + " " + xmlArgument + " \"" + path + "\"";
      Process process = Process.Start(this.psi);
      
      // HACK: Magic value.
      process.WaitForExit(10 * 1000);
      process.Close();
    }

    private string RipPuid()
    {
      // TODO: Verify file existence, previous operation could fail.
      XmlTextReader reader = new XmlTextReader(xmlPath);
      reader.ReadToFollowing("track");
      string puid = reader.GetAttribute("puid");
      reader.Close();
      return puid;
    }
  }
}
